import axios from "axios";
import { ElMessage } from "element-plus";
// 根据环境不同引入不同api地址
// create an axios instance
const hostname = window.location.hostname;
const protocol = window.location.protocol + "//";
console.log(hostname);
const baseCofig = {
  yydt: protocol + hostname,
  zcydt: protocol+hostname,
  // yydt: "https://yydt.yfzxzjysg.top",
  // zcydt: "https://zcydt.yfzxzjysg.top",
};
const service = axios.create({
  baseURL: baseCofig[import.meta.env.VITE_API_DEV_ENV], // url = base api url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request 拦截器 request interceptor
service.interceptors.request.use(
  (config) => {
    // 不传递默认开启loading
    // if (!config.hideloading) {
    //   // loading
    //   Toast.loading({
    //     forbidClick: true,
    //   });
    // }
    let token = sessionStorage.getItem("api-token");
    if (token) {
      config.headers["api-token"] = token;
    }
    return config;
  },
  (error) => {
    // do something with request error
    // console.log(error); // for debug
    return Promise.reject(error);
  }
);
// respone拦截器
service.interceptors.response.use(
  (response) => {
    // Toast.clear();
    const res = response.data;
    if (!res.success) {
      // 登录超时,重新登录
      ElMessage.error(res.msg);
      return Promise.reject(res || "error");
    } else {
      return Promise.resolve(res);
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
export default service;
